package com.fowo.api.common.mybatis.handlers;

import com.fowo.api.common.lang.DataId;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.sql.*;

@MappedTypes(DataId.class)
@MappedJdbcTypes(JdbcType.INTEGER)
public class DataIdTypeHandler extends BaseTypeHandler<DataId> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, DataId dataId, JdbcType jdbcType) throws SQLException {
        if (dataId.isNew()) {
            preparedStatement.setNull(i, Types.BIGINT);
            return;
        }
        preparedStatement.setLong(i, dataId.getId());
    }

    @Override
    public DataId getNullableResult(ResultSet resultSet, String s) throws SQLException {
        final String str = resultSet.getString(s);
        return StringUtils.hasText(str) ? new DataId(str) : null;
    }

    @Override
    public DataId getNullableResult(ResultSet resultSet, int i) throws SQLException {
        final String str = resultSet.getString(i);
        return StringUtils.hasText(str) ? new DataId(str) : null;
    }

    @Override
    public DataId getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        final String str = callableStatement.getString(i);
        return StringUtils.hasText(str) ? new DataId(str) : null;
    }
}
